#include "webcliwindow.h"
#include <QStackedLayout>

WebCliWindow::~WebCliWindow()
{
    delete m_webView;
}

void WebCliWindow::setUI(WebCliWindowUI *ui, bool showWebView)
{
    m_ui = ui;

    m_webView = new QWebEngineView(this);
    connect(m_webView, &QWebEngineView::loadStarted, this, []()->void{
        qInfo("web load started");
    });
    connect(m_webView, &QWebEngineView::loadFinished, this, [](bool ok)->void{
        qInfo("web load finished %d", ok);
    });
    connect(m_webView, &QWebEngineView::urlChanged, this, &WebCliWindow::onUrlChanged);
    QStackedLayout *layout = new QStackedLayout(m_ui->webViewCtn);
    m_ui->webViewCtn->setLayout(layout);
    layout->addWidget(m_webView);
    m_ui->webViewCtn->setVisible(showWebView);
}

void WebCliWindow::gotoURL(const QString &url, const QString &watchUrl)
{
    qInfo("goto url: %s", url.toStdString().c_str());
    m_watchUrl = watchUrl;
    m_webView->load(QUrl(url));
}

void WebCliWindow::onUrlChanged(const QUrl &url)
{
    qInfo("url changed: %s", url.url().toStdString().c_str());
    if(url.url().contains(m_watchUrl))
    {
        qInfo("hint game jump target");
        m_webView->stop();

        emit onEnterGame(url.query());
    }
}

void WebCliWindow::setProgressTip(const QString &tip)
{
    if(tip.isNull())
    {
        m_ui->textStatus->setVisible(false);
        m_ui->progressBar->setVisible(false);
    }
    else
    {
        m_ui->textStatus->setVisible(true);
        m_ui->textStatus->setText(tip);
        m_ui->progressBar->setVisible(true);
        m_ui->progressBar->setValue(0);
    }
}

void WebCliWindow::setProgressValue(qint64 bytesReceived, qint64 bytesTotal)
{
    m_ui->progressBar->setValue(bytesReceived / bytesTotal * 100.0f);
}
